package com.ztesoft.ossup.report.web;

import java.util.*;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.NOPLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.ztesoft.ossup.report.dao.JdbcTemplateDao;
import com.ztesoft.ossup.report.dao.ReportColumnGroupRepo;
import com.ztesoft.ossup.report.dao.ReportColumnRepo;
import com.ztesoft.ossup.report.dao.ReportConditionEnumRepo;
import com.ztesoft.ossup.report.dao.ReportConditionRepo;
import com.ztesoft.ossup.report.dao.ReportRepository;
import com.ztesoft.ossup.report.domain.Report;
import com.ztesoft.ossup.report.domain.ReportColumn;
import com.ztesoft.ossup.report.domain.ReportColumnGroup;
import com.ztesoft.ossup.report.domain.ReportCondition;
import com.ztesoft.ossup.report.domain.ReportConditionEnum;
import com.ztesoft.ossup.report.service.BaseService;
import com.ztesoft.ossup.report.service.DataPreviewService;
import com.ztesoft.ossup.report.service.PoiService;

@Controller
@RequestMapping("/outPut")
public class OutPutController extends BaseController {
	Logger _logger = Logger.getLogger(OutPutController.class);
	

    @Autowired
    ReportRepository reportRepository;
    
    @Autowired
    ReportConditionEnumRepo reportConditionEnumRepo;
    
    @Autowired
    ReportConditionRepo reportConditionRepo;
    
    @Autowired
    JdbcTemplateDao jdbcTemplateDao;
    
    @Autowired
    ReportColumnRepo reportColumnRepo;
    
    @Autowired
	DataPreviewService dataPreviewService;
    
    @Autowired
    PoiService poiService;
    @Autowired
    ReportColumnGroupRepo groupRepo;
    @Autowired
    BaseService baseService;

	 /**	
     * 获取条件数据
     * @param model
     * @return
     */
    @RequestMapping(value = "/conditionlist/{code}", method = RequestMethod.POST)
    @ResponseBody
    public Map getConditionList(@PathVariable String code, @RequestBody Map<String, Object> paramMap, Model model) {
    	
    	_logger.info("执行conditionlist方法(OutPutController主报表入口方法)");
    	_logger.info("传入code参数："+code);
    	long startTime = System.currentTimeMillis();
    	Map retMap = new HashMap();
    	try{
    		Report report = null;
        	List<Report> reportList= reportRepository.findByCode(code);//
        	if (reportList != null && reportList.size() > 0){
        		report = reportList.get(0);
        	}
        	_logger.info("传入reportId参数："+report.id);
        	List<ReportCondition> reportConditionList = reportConditionRepo.findByReportIdOrderBySortOrderAsc(report.id);
        	_logger.info("reportCondition参数："+reportConditionList.size());
        	List<ReportConditionEnum> reportConditionEnumlist = new ArrayList<ReportConditionEnum>();
        	List<Map> conditionValList = new ArrayList<Map>();

			//处理请求过来的参数
			String initParamStr = paramMap.get("paramStr")==null?"":paramMap.get("paramStr").toString();

			Map requestMap =new HashMap();
			if (!initParamStr.equals("")){
				String[] paramArray = initParamStr.split(",");
				for (int k = 0;k < paramArray.length;k++){
					String[] pArray = paramArray[k].split(":");
					requestMap.put(pArray[0],pArray[1]);
				}
			}

        	for (int i = 0; i < reportConditionList.size(); i++) {
        		ReportCondition repotCondition = reportConditionList.get(i);
        		if (repotCondition.getType().equals("3")){//选择框
        			if (repotCondition.getComboboxType() == 1){//静态数据
            			List<ReportConditionEnum> enumList = reportConditionEnumRepo.selectDataByStype(repotCondition.getEnumCode());
            			_logger.info("enumList参数："+enumList.size());
            			for (int j = 0; j < enumList.size(); j++) {
            				_logger.info("conditionid参数：");
        				}
            			reportConditionEnumlist.addAll(enumList);
            		}else if(repotCondition.getComboboxType() == 2){//sql 
            			if (repotCondition.dataSql != null && !repotCondition.dataSql.equals("")){
            				if (repotCondition.getCascadeCondition() == null || repotCondition.getCascadeCondition().equals("")){
								String conditionSql = repotCondition.dataSql;
								_logger.info("----处理前的条件查询sql："+conditionSql);
								if (!initParamStr.equals("")){
									Iterator itera = requestMap.entrySet().iterator();
									while(itera.hasNext()){
										_logger.info("---------处理报表条件Map数据----------");
										Map.Entry entry = (Map.Entry) itera.next();
										String pkey = entry.getKey().toString().toUpperCase();
										String pvalue = entry.getValue()==null?"":entry.getValue().toString();
										_logger.info(pkey+":"+pvalue);
										if (conditionSql.indexOf("#"+pkey+"#") > -1 && !pvalue.equals("")){
											conditionSql = conditionSql.replaceAll("#"+pkey+"#", "'"+pvalue+"'");
										}
									}
								}
								_logger.info("----处理好的条件查询sql："+conditionSql);
            					List<Map<String, Object>> conditionValuesList = jdbcTemplateDao.getConditionValues(conditionSql);
                				if(conditionValuesList != null && conditionValuesList.size() > 0 ){
                					for (Map<String, Object> valuesMap : conditionValuesList) {//在返回的Map中带conditionId
										String pcode = valuesMap.get("code")==null?"":valuesMap.get("code").toString();
										String vcode = valuesMap.get("CODE")==null?"":valuesMap.get("CODE").toString();
										String pname = valuesMap.get("name")==null?"":valuesMap.get("name").toString();
										String vname = valuesMap.get("NAME")==null?"":valuesMap.get("NAME").toString();
										_logger.info("pcode:"+pcode+",vcode:"+vcode+",pname:"+pname+",vname:"+vname);
										valuesMap.put("conditionId", repotCondition.id);
                						conditionValList.add(valuesMap);
            						}
                				}
            				}   				
            			}
            		}
        		}else if(repotCondition.getType().equals("2")){//1 输入框 2 时间框  3选择框
					String conditionVal = repotCondition.getDefaultVal() == null?"":repotCondition.getDefaultVal();
        			String defaultVal =dataPreviewService.transforDateForReport(conditionVal);
        			repotCondition.setDefaultVal(defaultVal);
        		}else if(repotCondition.getType().equals("1")){//1 输入框 2 时间框  3选择框
					String conditionVal  = repotCondition.getDefaultVal() == null? "":repotCondition.getDefaultVal();
        			if (conditionVal.equals("")){
        				repotCondition.setDefaultVal("");
        			}else {
						repotCondition.setDefaultVal(conditionVal);
					}
        		} 
    		}
        	_logger.info("reportConditionEnumlist参数："+reportConditionEnumlist.size());
        	retMap.put("enumList", reportConditionEnumlist);
        	retMap.put("reportCondition", reportConditionList);
        	retMap.put("conditionValList", conditionValList);
			_logger.info("conditionValList参数："+conditionValList.size());
        	retMap.put("reportId",report.id);
        	retMap.put("reportObj",report);

        	long endTime = System.currentTimeMillis();
        	_logger.info("加载主页条件耗时："+(endTime - startTime)/1000 +"秒");
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        return retMap;
    }	
    
    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    @ResponseBody
    public Map exportExcel(@RequestBody Map<String, Object> params){
    	
    	_logger.info("执行exportExcel方法(OutPutController报表导出方法)");
//    	@PathVariable String reportId {"reportId":"306","ITEM_NAME":"","ITEM_VAL":"","NAME":""}
    	String paramStr = (String) params.get("paramStr");
    	
    	List<Map<String, Object>> dataList = null;
    	List<ReportColumn> reportColList = null;
    	 List<ReportColumnGroup> reportColumnGroupList = null;
    	String fileName =getI18NMessage("common.report");//common.report
    	_logger.info("报表导出所传参数:"+paramStr);
    	//deal param string
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	String[] paramArray = paramStr.replace("{", "").replace("}", "").split(",");
    	for (String param : paramArray) {
    		String[] paramAndVal = param.split(":");
    		if (paramAndVal.length < 2){
    			continue;
    		}
    		paramMap.put(paramAndVal[0].replace("\"", ""), paramAndVal[1].replace("\"", ""));
		}
    	try{
    		//deal paramStr
    		String reportId = (String) paramMap.get("reportId");
    		reportId = reportId.replaceAll(",","");
        	_logger.info("reportI:"+reportId);
        	reportColList = reportColumnRepo.findByReportIdOrderBySortOrderAsc(Long.valueOf(reportId)); 
        	reportColumnGroupList = groupRepo.findByReportId(Long.valueOf(reportId));
        	_logger.info("reportColList:"+reportColList.size());
        	Report report = reportRepository.findOne(Long.valueOf(reportId));
        	fileName = report.getCode();
        	String dataSql = report.getSql();
        	if (dataSql != null && !dataSql.equals("")){
        		dataSql = baseService.doSql(dataSql, paramMap);
        		_logger.info("dataSql脚本是：" + dataSql);
            	dataList = jdbcTemplateDao.getConditionValues(dataSql);
            	_logger.info("dataList的大小：" + dataList.size());
        	}else{
        		_logger.error("报表查询sql为空，请详查！！");
        	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
//    	byte[] bytes = poiService.download(fileName, reportColList, dataList,reportColumnGroupList);
    	Map retMap = new HashMap();
    	retMap.put("reportColList", reportColList);
    	retMap.put("fileName",fileName);
    	retMap.put("dataList",dataList);
    	retMap.put("reportColumnGroupList",reportColumnGroupList);
    	return retMap;
    }
	
}
